﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SuiHan.Commons.Conf {
    public class ConfData : Dictionary<string, List<string>> {
        public string GetString(string key, string def = null) {
            return ContainsKey(key) ? base[key].FirstOrDefault() : def;
        }

        public string[] GetStringArray(string key) {
            string valueStr = GetString(key);
            return valueStr == null ? new string[] { } : valueStr.Split(',');
        }

        public int GetInt(string key) {
            return int.Parse(GetString(key));
        }

        public int GetInt(string key, int def) {
            string v = GetString(key);
            return string.IsNullOrWhiteSpace(v) ? def : int.Parse(v);
        }

        public double GetDouble(string key) {
            return double.Parse(GetString(key));
        }

        public double GetDouble(string key, double def) {
            string v = GetString(key);
            return string.IsNullOrWhiteSpace(v) ? def : double.Parse(v);
        }

        public long GetLong(string key) {
            return long.Parse(GetString(key));
        }

        public long GetLong(string key, long def) {
            string v = GetString(key);
            return string.IsNullOrWhiteSpace(v) ? def : long.Parse(v);
        }

        public bool GetBoolean(string key) {
            return bool.Parse(GetString(key));
        }

        public bool GetBoolean(string key, bool def) {
            string v = GetString(key);
            return string.IsNullOrWhiteSpace(v) ? def : bool.Parse(v);
        }

        public TEnum GetEnum<TEnum>(string key, TEnum def = default) where TEnum : struct, Enum {
            string v = GetString(key);
            if (string.IsNullOrWhiteSpace(v)) {
                return def;
            }

            Enum.TryParse(v, true, out TEnum ret);
            return ret;
        }
    }
}
